<?php
namespace frontend\modules\Api\controllers;

use common\models\TallyArap;
use common\models\TallyFuture;
use common\models\TallyRecord;
use common\services\TallyStatService;
use Yii;
use yii\filters\AccessControl;
use yii\helpers\ArrayHelper;

/**
 * Class StatController
 *
 * @package frontend\modules\Api\controllers
 * @desc 统计控制器 for 图表
 */
class StatController extends ApiController
{
    /**
     * @return array
     * 引入行为验证 过滤授权
     */
    public function behaviors()
    {
        $config = [
            'access' => [
                'class' => AccessControl::className(),
                'denyCallback' => function($rule, $action){
                    return self::failureResponse(100001, '请先登录!',[]);
                },
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ]
                ]
            ],
        ];
        return ArrayHelper::merge(parent::behaviors(), $config);
    }

    /**
     * @throws
     * 日常收支表 柱状堆积图使用
     */
    public function actionDaily()
    {
        $tallyId = Yii::$app->getRequest()->get('tally_id');
        if(!$tallyId){
            return self::failureResponse(500,'账本Id不能为空');
        }
        $this->checkRolePermission($this->_user['id'],$tallyId,'read');
        $condition = Yii::$app->request->post(); // type 等参数
        $result = TallyStatService::getDailyData($tallyId,null,$condition);
        return self::successResponse($result);
    }

    /**
     * @throws
     * 成员收支表 饼状图使用
     */
    public function actionMember()
    {
        $tallyId = Yii::$app->getRequest()->get('tally_id');
        if(!$tallyId){
            return self::failureResponse(500,'账本Id不能为空');
        }
        $this->checkRolePermission($this->_user['id'],$tallyId,'read');
        $condition = Yii::$app->request->post(); // type 等参数
        $result = TallyStatService::getMemberData($tallyId,null,$condition);
        return self::successResponse($result);
    }

    /**
     * @throws
     * 商家收支表 饼状图使用
     */
    public function actionStore()
    {
        $tallyId = Yii::$app->getRequest()->get('tally_id');
        if(!$tallyId){
            return self::failureResponse(500,'账本Id不能为空');
        }
        $this->checkRolePermission($this->_user['id'],$tallyId,'read');
        $condition = Yii::$app->request->post(); // type 等参数
        $result = TallyStatService::getStoreData($tallyId,null,$condition);
        return self::successResponse($result);
    }

    /**
     * 获取年度统计 返回月度统计
     * @throws \yii\base\ExitException
     */
    public function actionMonthy()
    {
        $tallyId = Yii::$app->getRequest()->get('tally_id');
        if(!$tallyId){
            return self::failureResponse(500,'账本Id不能为空');
        }
        $this->checkRolePermission($this->_user['id'],$tallyId,'read');
        $condition = Yii::$app->request->post(); // type 等参数
        $result = TallyStatService::getStatMonthy($tallyId,null,$condition);
        return self::successResponse($result);
    }
    public function actionCatrgoryIn(){
        $tallyId = Yii::$app->getRequest()->get('tally_id');
        if(!$tallyId){
            return self::failureResponse(500,'账本Id不能为空');
        }
        $project_id = Yii::$app->getRequest()->post('project_id');
        $condition = Yii::$app->getRequest()->post();
        //查询账本下的收入分类
        $query = TallyRecord::find()
            ->select('sum(`amount`) as total,category_id,category_name as name')
            ->where(['tally_id'=>$tallyId,'state'=>TallyRecord::STATE_VALID,'type'=>10]);
        if($project_id != ''){
            $query = $query->andFilterWhere(['=','project_id',$project_id])->groupBy('category_parent_id');
        }
        if(isset($condition['begin_date']) && isset($condition['end_date'])) {
            if($condition['begin_date'] != '' && $condition['end_date'] != '') {
                $condition['end_date'] = date('Y-m-d',strtotime('+1 day',strtotime($condition['end_date'])));
                $query->andFilterWhere(['between','tally_time',$condition['begin_date'], $condition['end_date']]);
            }
        }
        
        $bQuery = TallyRecord::find()
            ->select('sum(`amount`) as total,category_id,category_name as name')
            ->where(['tally_id'=>$tallyId,'state'=>TallyRecord::STATE_VALID,'type'=>20]);
        if($project_id != ''){
            $bQuery = $bQuery->andFilterWhere(['=','project_id',$project_id])->groupBy('category_parent_id');
        }
        if(isset($condition['begin_date']) && isset($condition['end_date'])) {
            if($condition['begin_date'] != '' && $condition['end_date'] != '') {
                $condition['end_date'] = date('Y-m-d',strtotime('+1 day',strtotime($condition['end_date'])));
                $bQuery->andFilterWhere(['between','tally_time',$condition['begin_date'], $condition['end_date']]);
            }
        }

        return self::successResponse([
            'outlist'=>$query->asArray()->all(),
            'inlst'=>$bQuery->asArray()->all()
        ]);
    }

    /**
     * 获取月度统计 返回每天统计
     * @throws \yii\base\ExitException
     */
    public function actionDay()
    {
        $tallyId = Yii::$app->getRequest()->get('tally_id');
        if(!$tallyId){
            return self::failureResponse(500,'账本Id不能为空');
        }
        $this->checkRolePermission($this->_user['id'],$tallyId,'read');
        $condition = Yii::$app->request->post(); // type 等参数
            $result = TallyStatService::getStatDay($tallyId,null,$condition);
        return self::successResponse($result);
    }

    public function actionGuaCountDebt(){

        $tallyId = Yii::$app->getRequest()->get('tally_id');
        if(!$tallyId){
            return self::failureResponse(500,'账本Id不能为空');
        }
        $project_id = Yii::$app->getRequest()->post('project_id');
        //查询项目的挂账情况
        $tally_arap_query = TallyArap::find()->where([
            'project_id'=>$project_id,
            'tally_id'=>$tallyId,
            'type'=>10
        ]);
        if(isset($condition['begin_date']) && isset($condition['end_date'])) {
            if($condition['begin_date'] != '' && $condition['end_date'] != '') {
                $condition['end_date'] = date('Y-m-d',strtotime('+1 day',strtotime($condition['end_date'])));
                $tally_arap_query->andFilterWhere(['between','tally_time',$condition['begin_date'], $condition['end_date']]);
            }
        }
        if(isset($condition['store_id'])){
            $tally_arap_query->andFilterWhere(['=','store_id',$condition['store_id']]);
        }


        $clone_arap_query = TallyArap::find()->where([
            'project_id'=>$project_id,
            'tally_id'=>$tallyId,
            'type'=>20
        ]);
        if(isset($condition['begin_date']) && isset($condition['end_date'])) {
            if($condition['begin_date'] != '' && $condition['end_date'] != '') {
                $condition['end_date'] = date('Y-m-d',strtotime('+1 day',strtotime($condition['end_date'])));
                $clone_arap_query->andFilterWhere(['between','tally_time',$condition['begin_date'], $condition['end_date']]);
            }
        }
        if(isset($condition['store_id'])){
            $clone_arap_query->andFilterWhere(['=','store_id',$condition['store_id']]);
        }


        return self::successResponse([
            'data'=>[
                ['name'=>'应收总额','total'=>$tally_arap_query->sum('amount')],
                ['name'=>'应付总额','total'=>$clone_arap_query->sum('amount')],
            ]
        ]);
    }





    public function actionYuShouCountDebt(){
        $tallyId = Yii::$app->getRequest()->get('tally_id');
        if(!$tallyId){
            return self::failureResponse(500,'账本Id不能为空');
        }
        $project_id = Yii::$app->getRequest()->post('project_id');
        //查询项目的挂账情况
        $tally_arap_query = TallyFuture::find()->where([
            'project_id'=>$project_id,
            'tally_id'=>$tallyId,
            'type'=>10
        ]);
        if(isset($condition['begin_date']) && isset($condition['end_date'])) {
            if($condition['begin_date'] != '' && $condition['end_date'] != '') {
                $condition['end_date'] = date('Y-m-d',strtotime('+1 day',strtotime($condition['end_date'])));
                $tally_arap_query->andFilterWhere(['between','tally_time',$condition['begin_date'], $condition['end_date']]);
            }
        }


        if(isset($condition['store_id'])){
            $tally_arap_query->andFilterWhere(['=','store_id',$condition['store_id']]);
        }

        $clone_arap_query = TallyFuture::find()->where([
            'project_id'=>$project_id,
            'tally_id'=>$tallyId,
            'type'=>20
        ]);

        if(isset($condition['store_id'])){
            $clone_arap_query->andFilterWhere(['=','store_id',$condition['store_id']]);
        }
        if(isset($condition['begin_date']) && isset($condition['end_date'])) {
            if($condition['begin_date'] != '' && $condition['end_date'] != '') {
                $condition['end_date'] = date('Y-m-d',strtotime('+1 day',strtotime($condition['end_date'])));
                $clone_arap_query->andFilterWhere(['between','tally_time',$condition['begin_date'], $condition['end_date']]);
            }
        }

        return self::successResponse([
            'data'=>[
                ['name'=>'预收总额','total'=>$tally_arap_query->sum('amount')],
                ['name'=>'预付总额','total'=>$clone_arap_query->sum('amount')],
            ]
        ]);
    }


}
